#include <syslog.h>
#include <time.h>
#include "RequestWeightJsonQuery.h"
#include "qjson/parser.h"
#include "qjson/serializer.h"
#include <QVariant>
#include <QVariantMap>
#include <QVector>
#include "DbSession.h"
#include <QDate>

RequestWeightJsonQuery::RequestWeightJsonQuery()
{
}

void RequestWeightJsonQuery::init(const std::stringstream& query)
{
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse(
            QByteArray(query.str().c_str()), &ok).toMap();
    if (!ok)
    {
        // print error in log
    }
    else
    {
        m_token = result["auth_token"].toString();
    }

    m_status = "Error";
}

void RequestWeightJsonQuery::process()
{
    int userId = DbSession::getInstance().getUserIdByToken(m_token);

    if (!userId)
    {
        m_status = "Error";
    }
    else
    {
        if (DbSession::getInstance().getUser(userId)->getWeights()->count() > 0)
        {
            m_weight = DbSession::getInstance().getUser(userId)->getWeights()->last()->getWeight();
            m_date = DbSession::getInstance().getUser(userId)->getWeights()->last()->getDate().toString("dd-MM-yyyy");
        }
        else
        {
            m_weight = 0;
            m_date = "01-01-1970";
        }
        m_status = "Ok";

    }

}

std::string RequestWeightJsonQuery::outToString() const
{
    if(m_status=="Error")
    {
        //return "{\"status\":\"" + m_status.toStdString() + "\"}";
    }
    else
    {
        QVariantMap request;
        request.insert("status", m_status);
        if (m_status == "Ok");
        {
            request.insert("weight", m_weight);
            request.insert("date", m_date);
        }

        QJson::Serializer serializer;
        QString json(serializer.serialize(request));

        return json.toStdString();
    }
}
